<?php
/**
 * Created by PhpStorm.
 * User: mww
 * Date: 2018/12/17
 * Time: 16:08
 */
namespace app\api\controller;
use think\Db;
class Selfcar extends Base
{
    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {
        header('Access-Control-Allow-Origin:*');
        extract(input());
        if($user_id != 0){
            $auth = $this->checkAll($user_id,$time,$value,$reqKey);
            if($auth == 112){
                echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
                exit;
            }elseif($auth == 110){
                echo json_encode(['status' => 302, 'msg' => $this->frost]);
                exit;
            }elseif($auth == 1103){
                echo json_encode(['status' => 303, 'msg' => $this->del]);
                exit;
            }
        }

    }


    /**
     * 加入购物车
     */
    public function putGoodsIncar()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        $data = [
            'user_id' => $user_id,
            'goods_id' => $good_id,
            'attr_id' => $attr_id,
            'num' => $num,
            'created_at' => $today,
            'updated_at' => $today,
        ];
        //库存
        $stock = Db::table('up_self_goods_attr')
            ->where('attr_id',$attr_id)
            ->value('stock');
        if($stock < $num){
            return json(['status'=>0,'msg'=>'库存不足']);
        }
        //是否相同
        $have = Db::table('up_self_car')
            ->where('user_id',$user_id)
            ->where('goods_id',$good_id)
            ->where('attr_id',$attr_id)
            ->find();
        if($have){
            $res = Db::table('up_self_car')->where('id',$have['id'])->setInc('num',1);
        }else{
            $res = Db::table('up_self_car')
                ->insert($data);
        }

        if($res){
            return json(['status'=>200,'msg'=>'ok']);
        }else{
            return json(['status'=>0,'msg'=>'加入购物车失败，请刷新重试']);
        }
    }
    /**
     * 我的购物车
     */
    public function mycar()
    {
        extract(input());
        $field = 'id,num,good_id,good_name,price,good_thumb,sign_str';
        $field .= ',good_status,stock,is_delete';
        $cars = Db::table('up_self_car')->alias('c')
            ->join('up_self_goods g','c.goods_id=g.good_id','LEFT')
            ->join('up_self_goods_attr a','c.attr_id=a.attr_id','LEFT')
            ->where('user_id',$user_id)
            ->where('car_type',1)
            ->field($field)
            ->order('updated_at DESC')
            ->page($page,10)
            ->select();
        if($cars){
            foreach ($cars as $k=>$v){
                $good_sta = $v['good_status'];
                $attr_sta_stock = $v['stock'];
                $attr_sta_del = $v['is_delete'];
                if($good_sta == 1 && $attr_sta_stock > 0 && $attr_sta_del == 0){
                    Db::table('up_self_car')->where('id',$v['id'])->setField('status',1);
                }
                if($good_sta == 2){
                    Db::table('up_self_car')->where('id',$v['id'])->setField('status',4);
                }else{
                    if($attr_sta_stock <= 0){
                        Db::table('up_self_car')->where('id',$v['id'])->setField('status',2);
                    }
                    if($attr_sta_del == 1){
                        Db::table('up_self_car')->where('id',$v['id'])->setField('status',3);
                    }
                }

            }
        }
        return json(['status'=>200,'msg'=>$cars]);
    }
    /**
     * 购物车——加减
     * type：1是加2是减
     */
    public function carUpDown()
    {
        extract(input());
        $car = Db::table('up_self_car')->where('id',$id)->find();
        if($car['car_type'] == 1){
            $stock = Db::table('up_self_goods_attr')
                ->where('attr_id',$car['attr_id'])
                ->value('stock');
        }else{
            $stock = 1000;
        }
        if($type == 1){
            if($car['num'] >= $stock){
                return json(['status'=>0,'msg'=>'库存不足']);
            }else{
                $res = Db::table('up_self_car')->where('id',$id)->setInc('num',1);
            }
        }else{
            if($car['num'] <= 1){
                return json(['status'=>0,'msg'=>'不能再减了哦']);
            }else{
                $res = Db::table('up_self_car')->where('id',$id)->setDec('num',1);
            }
        }
        if($res){
            return json(['status'=>200,'msg'=>'ok']);
        }else{
            return json(['status'=>0,'msg'=>'加入购物车失败，请刷新重试']);
        }
    }
    /**
     * 购物车——删除
     */
    public function carDel()
    {
        extract(input());
        $ids = trim($ids,',');
        $res = Db::table('up_self_car')->where('id','in',$ids)->delete();
        if($res){
            return json(['status'=>200,'msg'=>'ok']);
        }else{
            return json(['status'=>0,'msg'=>'加入购物车失败，请刷新重试']);
        }
    }
    /**
     * 提交订单，查看订单详情（立即购买展示）
     * 其实要根据运费来计算
     * address_id：传就给这个地址，不传给默认的地址
     */
    public function sureOrder()
    {
        extract(input());
        $data = $this->lijigoumai($good_id,$attr_id,$num);
        if($data['status'] != 200){
            return json($data);
        }else{
            $good = $data['msg'];
        }
        //默认收货地址
        if(!isset($address_id) || empty($address_id)){
            $address_id = '';
        }
        $address = $this->myAddressInfo($user_id,$address_id);
        if(empty($address)){
            $address = '';
        }
        return json(['status'=>200,'msg'=>$good,'address'=>$address,'sondata'=>[]]);
    }
    /**
     * 提交订单，查看订单详情（购物车处展示）
     * 其实要根据运费来计算
     * ids：购物车id字符串
     */
    public function sureOrderCar()
    {
        extract(input());
        $have = Db::table('up_self_car')
            ->where('id','in',$ids)
            ->find();
        if($have['car_type'] == 1){
            $data = $this->gouwuche($ids);
            if($data['status'] != 200){
                return json($data);
            }
            //默认收货地址
            if(!isset($address_id) || empty($address_id)){
                $address_id = '';
            }
            $address = $this->myAddressInfo($user_id,$address_id);
            if(empty($address)){
                $address = '';
            }
            $data['address'] = $address;
            $data['sondata'] = [];
        }else{
            $can = $this->getSonByUser($user_id);
            if($can['status'] != 200){
                return json_encode($can);
            }
            $sondata = $can['msg'];
            $data = $this->gouwucheps($ids,$sondata);
            if($data['status'] != 200){
                return json($data);
            }
            //默认收货地址
            if(!isset($address_id) || empty($address_id)){
                $address_id = '';
            }
            $address = $this->myAddressInfo($user_id,$address_id);
            if(empty($address)){
                $address = '';
            }
            $data['address'] = $address;
            $data['sondata'] = $sondata;
        }

        return json($data); //购物车商品数据、价格、地址
    }
    /**
     * 购买
     * type：1 单商品购买，2购物车购买
     *
     */
    public function payOrder()
    {
        extract(input());
//        $type = 2;
//        $address_id = 1;
//        $remark = '';
//        $pay_type = 1;
//        $ids = '1';
//        $user_id = 9;
//        return json_encode(['status'=>0,'msg'=>$type.$address_id.$remark.$pay_type.$ids.$user_id]);
        $today = date('Y-m-d H:i:s');
        $address = $this->myAddressInfo($user_id,$address_id);
        if(!$address['sheng'] || !$address['shi'] || !$address['qu'] || !$address['address_detail']){
            return json_encode(['status'=>0,'msg'=>'地址不能为空，请重新选择或新建~']);
        }
        $number = date('YmdHis') . rand(1000000,9999999);
        $zhi_xia = [
            '北京','天津','重庆','上海'
        ];
        if(in_array($address['sheng'],$zhi_xia)){
            $address['sheng'] = '';
        }
        $order = [
            'user_id' => $user_id,
            'order_no' => $number,
            'name' => $address['address_name'],
            'mobile' => $address['address_phone'],
            'address' => $address['sheng'] . $address['shi'] . $address['qu'] . $address['address_detail'],
            'remark' => $remark,
            'pay_type' => $pay_type,
            'pay_time' => $today,
            'created_at' => $today,
            'updated_at' => $today,
            'updated_at' => $today,
        ];
        if(empty($order['address'])){
            return json_encode(['status'=>0,'msg'=>'地址不能为空，请重新选择或新建~']);
        }
        Db::startTrans();
        try{
            if($type == 1){
                $pay_year = 0;
                $user_son_id = 0;
                if($contract == 1){
                    $data = $this->lijigoumai($good_id,$attr_id,$num);
                    if($data['status'] != 200){
                        Db::rollback();
                        return json($data);
                    }
                    $unique_code = '';
                }else{
                    $can = $this->getSonByUser($user_id);
                    if($can['status'] != 200){
                        return json_encode($can);
                    }
                    $sondata = $can['msg'];
                    if(isset($nowyear) && $nowyear){
                        $sondata['uson_year'] = $nowyear;
                    }
                    $insize = $this->getInSizeForGood($good_id,$attr_id);
                    if($insize == false){
                        return json(['status'=>0,'msg'=>'请重新选择尺码']);
                    }
                    $data = $this->lijigoumaips($good_id,$attr_id,$num,$sondata);
                    if($data['status'] != 200){
                        Db::rollback();
                        return json($data);
                    }
                    $user_son_id = $sondata['uson_id'];
                    $order['order_contract'] = 2;
                    $order['order_user_son_id'] = $user_son_id;
                    $order['order_school'] = Db::table('up_school')->where('school_id',$sondata['uson_school'])->value('school_erp');
                    //>>>>>>>>>>>>>>>>>>>获取唯一编码start>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
                    $less_code = Db::table('up_good_spec')
                        ->where('spec_good_coding_less',$data['msg']['good_coding_less'])
                        ->where('spec_size',$attr_id)
                        ->where('spec_size_q',2)
                        ->value('spec_good_coding_less');
                    if($less_code){ //说明此款号有Q款，再去判断
                        $erp = 2;
                    }else{
                        $erp = 1;//压根没有Q款
                    }
                    if(isset($nowyear) && $nowyear){
                        $sondata['uson_year'] = $nowyear;
                    }
                    $pay_year = $sondata['uson_year'];
                    $sure = $this->getStudentGoods($sondata['uson_school'],$sondata['uson_year'],$sondata['user_gender'],$erp,$data['msg']['good_coding_less']);
                    $size_code = Db::table('up_good_spec')
                        ->where('spec_good_coding_less',$data['msg']['good_coding_less'])
                        ->where('spec_size',$attr_id)
                        ->where('spec_size_q',$sure['sg_good_q'])
                        ->value('spec_size_two');
                    if(empty($size_code)){
                        Db::rollback();
                        return json_encode(['status'=>0,'msg'=>'尺码有误，请刷新重试，或重新选择尺码~']);
                    }
                    $unique_code = $sure['sg_good_coding'] . $size_code;
                    if($sure['sg_sign']){
                        $unique_code .= $sure['sg_sign'];
                    }
                    //年份和交期
                    $time = time();
                    $days = Db::table('up_about')->where('id',10)->value('content');
                    $days = (int)$days;
                    $days_after = date("Ymd",($time + 3600*$days*24));
                    $order['order_erp_year'] = $sure['sg_year'];
                    $order['order_erp_done'] = $days_after;
                    //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<获取唯一编码end<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
                }

                $good = $data['msg'];
                $order['total_price'] = $good['allprice'];
                $order['express_original_price'] = $good['postman'];
                $order['all_goods_price'] = $good['allprice'] - $good['postman'];
                $order_id = Db::table('up_self_order')->insertGetId($order);
                $detail = [
                    'order_id' => $order_id,
                    'detail_user_son_id' => $user_son_id,
                    'goods_id' => $good_id,
                    'goods_coding_unique' => $unique_code,
                    'num' => $num,
                    'unit_price' => $good['price'],
                    'attr_id' => $attr_id,
                    'goods_info' => $good['sign_str'],
                    'created_at' => $today,
                    'updated_at' => $today,
                    'pay_year' => $pay_year,
                ];
                Db::table('up_self_order_detail')->insertGetId($detail);
                if($contract == 1){
                    //减attr库存、减good库存、加销量(支付成功再加销量)
                    Db::table('up_self_goods')->where('good_id',$good_id)->setDec('good_stock',$num);
                    Db::table('up_self_goods_attr')->where('attr_id',$attr_id)->setDec('stock',$num);
                    //为了后台的商品名字和总数量
                }
                Db::table('up_self_order')->where('order_id',$order_id)->update([
                    'first_good_name' => $good['good_name'],
                    'all_good_nums' => $num
                ]);
            }else{
                $pay_year = 0;
                $user_son_id = 0;
                $car = Db::table('up_self_car')
                    ->where('id','in',$ids)
                    ->find();
                $unique_code = '';
                if($car['car_type'] == 1){
                    $data = $this->gouwuche($ids);
                    if($data['status'] != 200){
                        Db::rollback();
                        return json($data);
                    }
                }else{
                    $can = $this->getSonByUser($user_id);
                    if($can['status'] != 200){
                        return json_encode($can);
                    }
                    $sondata = $can['msg'];
                    $data = $this->gouwucheps($ids,$sondata);
                    if($data['status'] != 200){
                        Db::rollback();
                        return json($data);
                    }
                    $user_son_id = $sondata['uson_id'];
                    $order['order_contract'] = 2;
                    $order['order_user_son_id'] = $user_son_id;
                    $order['order_school'] = Db::table('up_school')->where('school_id',$sondata['uson_school'])->value('school_erp');
                }

                //-------------------------------------
                Db::table('up_self_car')
                    ->where('id','in',$ids)
                    ->delete();
                //-------------------------------------
                $cars = $data['msg'];
                $price_data = $data['price_data'];
                $order['total_price'] = $price_data['allprice'];
                $order['express_original_price'] = $price_data['postman'];
                $order['all_goods_price'] = $price_data['allprice'] - $price_data['postman'];
                $order_id = Db::table('up_self_order')->insertGetId($order);
                //为了后台的商品名字和总数量
                $num = 0;
                $first_good_name = '';
                $order_erp_year = '';
                $order_erp_done = '';
                if($car['car_type'] != 1) {
                    $surearray = $this->getStudentGoodsByForeach($sondata['uson_school'], $sondata['uson_year'], $sondata['user_gender'], $cars);
                    //年份和交期
                    $time = time();
                    $days = Db::table('up_about')->where('id',10)->value('content');
                    $days = (int)$days;
                    $days_after = date("Ymd",($time + 3600*$days*24));
                    $order_erp_year = $surearray[0]['sg_year'];
                    $order_erp_done = $days_after;
                }
                foreach ($cars as $k=>$v){
                    //>>>>>>>>>>>>>>>>>>>获取唯一编码start>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
                    if($car['car_type'] != 1) {
                        $sure = $surearray[$k];
                        $size_code = Db::table('up_good_spec')
                            ->where('spec_good_coding_less', $v['good_coding_less'])
                            ->where('spec_size', $v['attr_id'])
                            ->where('spec_size_q', $sure['sg_good_q'])
                            ->value('spec_size_two');
                        if(empty($size_code)){
                            Db::rollback();
                            return json_encode(['status'=>0,'msg'=>'尺码有误，请刷新重试，或重新选择尺码~']);
                        }
                        $unique_code = $sure['sg_good_coding'] . $size_code;
                        if ($sure['sg_sign']) {
                            $unique_code .= $sure['sg_sign'];
                        }
                        $pay_year = $sure['sg_year'];
                    }
                    //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<获取唯一编码end<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
                    //为了后台的商品名字和总数量
                    $num += $v['num'];
                    if($k == 0){
                        $first_good_name = $v['good_name'];
                    }
                    //
                    $detail = [
                        'order_id' => $order_id,
                        'detail_user_son_id' => $user_son_id,
                        'goods_id' => $v['good_id'],
                        'goods_coding_unique' => $unique_code,
                        'num' => $v['num'],
                        'unit_price' => $v['price'],
                        'goods_info' => $v['sign_str'],
                        'attr_id' => $v['attr_id'],
                        'created_at' => $today,
                        'updated_at' => $today,
                        'pay_year' => $pay_year,
                    ];
                    $a = Db::table('up_self_order_detail')->insertGetId($detail);
                    if($car['car_type'] == 1){
                        //减attr库存、减good库存、加销量(支付成功再加销量)
                        Db::table('up_self_goods')->where('good_id',$v['good_id'])->setDec('good_stock',$v['num']);
                        Db::table('up_self_goods_attr')->where('attr_id',$v['attr_id'])->setDec('stock',$v['num']);
                    }
//                    增补商品或者统购的就不减了，因为有没有都得发货
                }
                //为了后台的商品名字和总数量
                Db::table('up_self_order')->where('order_id',$order_id)->update([
                    'first_good_name' => $first_good_name,
                    'all_good_nums' => $num,
                    'order_erp_year' => $order_erp_year,
                    'order_erp_done' => $order_erp_done,
                ]);
            }
            Db::commit();
//--------------------支付方式------------------
            if($pay_type == 1){
                $payorder = array();
                $payorder['body'] = '派逊商城'; // 描述
                $payorder['total_fee'] = $order['total_price']*100; // 订单金额
                $payorder['out_trade_no'] = $number; // 订单号
                $payorder['product_id'] = ''; // 产品ID
                $payorder['trade_type'] = 'APP'; // 类型
                $mww_weixinpay =  new \app\api\controller\Weixin();
                $respont = $mww_weixinpay->WeChatPayReady($payorder);
                return json_encode(['status'=>200,'msg'=>$respont,'order_id'=>$order_id,'pay_type'=>$pay_type,'total_price'=>$order['total_price']]);
            }elseif($pay_type == 2){
                $mww_alipay =  new \app\api\controller\Ali();
                $respont = $mww_alipay->getParam($number, $order['total_price'], '派逊商城', '派逊商城');
                $respont['order_id'] = $order_id;
                $respont['pay_type'] = $pay_type;
                $respont['total_price'] = $order['total_price'];
                return json_encode($respont);
            }else{
                return json_encode(['status'=>0,'msg'=>'暂未开放，敬请期待~']);
                $mww_yinlianpay =  new \app\api\controller\Upacp();
                $respont = $mww_yinlianpay->UpacpPayTn($number, $order['total_price']*100);
                $respont['order_id'] = $order_id;
                $respont['pay_type'] = $pay_type;
                $respont['total_price'] = $order['total_price'];
                //生产环境APP端请求地址：https://gateway.95516.com/gateway/api/appTransReq.do
                $respont['app_url'] = 'https://gateway.test.95516.com/gateway/api/appTransReq.do';
                return json_encode($respont);
            }
        }catch (\Exception $e) {
            Db::rollback();
            return json_encode(['status'=>0,'msg'=>'生成订单失败，请刷新重试~']);
        }
    }
    /**
     * 单独为取消订单做的支付：onlyPay
     * @return string
     * $so_id,$type
     */
    public function onlyPay()
    {
        extract(input());
        $is_pay = Db::table('up_self_order')->where('order_id', $order_id)->value('is_pay');
        if($is_pay != 0){
            return json_encode(['status'=>0,'msg'=>'只有未支付订单才可以继续支付']);
        }
        $order = array();
        $number = date('YmdHis') . rand(1000000, 9999999);
        $order['order_no'] = $number;
        $order['pay_type'] = $pay_type;
        $pay = Db::table('up_self_order')->where('order_id', $order_id)->value('total_price');
        $res = Db::table('up_self_order')->where('order_id', $order_id)->update($order);
        if($res){
            if($pay_type == 1){
                $order = array();
                $order['body'] = '派逊商城'; // 描述
                $order['total_fee'] = $pay*100; // 订单金额
                $order['out_trade_no'] = $number; // 订单号
                $order['product_id'] = ''; // 产品ID
                $order['trade_type'] = 'APP'; // 类型
                $mww_weixinpay =  new \app\api\controller\Weixin();
                $respont = $mww_weixinpay->WeChatPayReady($order);
                return json_encode(['status'=>200,'msg'=>$respont]);
            }elseif($pay_type == 2){
                $mww_alipay =  new \app\api\controller\Ali();
                $respont = $mww_alipay->getParam($number, $pay, '派逊商城', '派逊商城');
                return json_encode($respont);
            }else{
                $mww_yinlianpay =  new \app\api\controller\Upacp();
                $respont = $mww_yinlianpay->UpacpPayTn($number, $pay*100);
                $respont['app_url'] = 'https://gateway.test.95516.com/gateway/api/appTransReq.do';
                return json_encode($respont);
            }
        }else{
            return json_encode(['status'=>0,'msg'=>'订单号更改失败']);
        }

    }
}